#include "util.h"
#include <string>
#include <sstream>
#include <iomanip>

int util::char2int(char c)
{
	if (c >= '0'&& c <= '9')
		return c - '0';
	else if (c >= 'A' && c <= 'F')
		return c - 'A' + 10;
	else if (c >= 'a' && c <= 'f')
		return c - 'a' + 10;
	return -1;
}

std::string util::hex2str(const std::string& in)
{
	if (in.length() & 1)
		return in;
	static std::string ptn = "0123456789ABCDEFabcdef";
	size_t found = in.find_first_not_of(ptn);
	if (found != in.npos)
		return in;

	std::string out;
	out.reserve(in.length() >> 1);
	for (size_t pos = 0; pos < in.length(); pos += 2)
		out.push_back((char2int(in[pos]) << 4) | char2int(in[pos + 1]));
	return out;
}

std::string util::str2hex(const std::string& in)
{
	std::stringstream hValStr;
	for (std::size_t i = 0; i < in.length(); i++)
	{
		int hValInt = (char)in[i];
		hValStr << std::hex << std::setw(2) << std::setfill('0') << hValInt;
	}

	return hValStr.str();
}
